<template>
    <el-form ref="baseForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
            <el-col :span="12">
            <el-form-item label="代码标识" prop="moduleName">
                <el-input v-model="form.moduleName"></el-input>
            </el-form-item>
            </el-col><el-col :span="12">
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
            <el-form-item label="模型类型" prop="dataType">
                <dx-select v-model="form.dataType" :disabled="isEdit" placeholder="请选择" codeType="DATA_MODEL_TYPE" @change="dataTypeChange"></dx-select> 
            </el-form-item>
            </el-col><el-col :span="12">
            <el-form-item label="分类" prop="categories">
                <dx-select v-model="form.categories" placeholder="请选择" codeType="CODE_MODEL_CATEGROIES"></dx-select> 
            </el-form-item>
            </el-col>
        </el-row>
        <el-row v-if="form.dataType=='sql'">
            <el-col :span="24">
                <el-form-item label="SQL" prop="sqlText" :rules="{ required: true, message: '请输入SQL文本', trigger: 'blur' }">
                    <el-input type="textarea" :rows="6" v-model="form.sqlText"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row v-if="form.dataType=='table'">
            <el-col :span="11">
                <el-form-item label="表名" prop="tableName" :rules="{ required: true, message: '请输入表名', trigger: 'blur' }">
                    <dx-select v-model="form.tableName" :disabled="isEdit" codeType="zhhw_table_names_code"></dx-select>
                </el-form-item>
            </el-col>
            <el-col :span="1"><el-button type="primary" v-if="form.tableName" @click="getFields">映射</el-button></el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="AI" prop="actionIntercept">
                     <dx-select v-model="form.actionIntercept" placeholder="请选择" codeType="action_intercept_codelist" :clearable="true"></dx-select> 
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
            <el-form-item label="排序" prop="orderList">
                <el-input v-model="form.orderList"></el-input>
            </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="启用" prop="enable">
                <el-switch v-model="form.enable"></el-switch>
            </el-form-item>
            </el-col>
        </el-row>
        
        <el-row v-if="form.dataType!='table'">
            <el-button type="primary" size="small" @click="addRow()" style="margin-bottom:10px;"><i class="el-icon-plus"></i>增加字段</el-button>
            <el-table class="fieldTable" :data="form.fields" border stripe style="width:100%" :key="index">
                <el-table-column fixed type="index" label="序号" width="50"></el-table-column>
                <el-table-column fixed label="字段" width="160">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.columnName"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="字段类型" width="120">
                    <template slot-scope="scope">
                        <dx-select codeType="datamodel_jdbctype_code" v-model="scope.row.columnType"></dx-select>
                    </template>
                </el-table-column>
                <el-table-column label="字段名称" width="120">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.columnLabel"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="代码模型" width="180">
                    <template slot-scope="scope">
                        <dx-treeselect v-model="scope.row.codeType" :expandLevel="1" codeType="codemodel_treelist" :leafable="true" :filterable="true" :clearable="true"></dx-treeselect>
                    </template>
                </el-table-column>
              
                <el-table-column label="描述">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remark"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="主键" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.pk"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="自增" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.autoIncrement"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="非空" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.notNull"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="唯一值" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isUnique"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="生成策略" width="120" align="center">
                    <template slot-scope="scope">
                        <dx-select v-model="scope.row.pkGenerator" codeType="PK_GENERATOR_TYPE" :clearable="true"></dx-select>
                    </template>
                </el-table-column>
                <el-table-column label="默认SCOPE" width="120" align="center">
                    <template slot-scope="scope">
                        <dx-select v-model="scope.row.defaultScope" codeType="defaultvalue_scope_dict" :clearable="true"></dx-select>
                    </template>
                </el-table-column>
                
                <el-table-column label="默认值"  width="200" align="center">
                    <template slot-scope="scope">
                        <dx-suggesttext v-model="scope.row.defaultValue" :clearable="true" codeType="datamodel_defaultvalue_code"></dx-suggesttext>
                    </template>
                </el-table-column>
                <el-table-column label="转换器" width="200" align="center">
                    <template slot-scope="scope">
                        <dx-select v-model="scope.row.converter" :clearable="true" codeType="datamodel_conerter_code"></dx-select>
                    </template>
                </el-table-column>
                <el-table-column label="排序" width="80" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.orderList"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="deleteRow(scope.$index,scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <el-row v-else>
            <el-table class="fieldTable" :data="form.fields" border stripe style="width:100%" :key="index">
                <el-table-column fixed type="index" label="序号" width="50"></el-table-column>
                <el-table-column fixed label="字段" width="160">
                    <template slot-scope="scope">{{scope.row.columnName}}</template>
                </el-table-column>
                <el-table-column label="字段类型" width="120">
                    <template slot-scope="scope">
                        <dx-text codeType="datamodel_jdbctype_code" :value="scope.row.columnType"></dx-text>
                    </template>
                </el-table-column>
                <el-table-column label="字段名称" width="120">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.columnLabel"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="代码模型" width="180">
                    <template slot-scope="scope">
                        <dx-treeselect v-model="scope.row.codeType" :expandLevel="1" codeType="codemodel_treelist" :leafable="true" :filterable="true" :clearable="true"></dx-treeselect>
                    </template>
                </el-table-column>
              
                <el-table-column label="描述">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remark"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="主键" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.pk"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="自增" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.autoIncrement"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="唯一" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isUnique" :disabled="scope.row.pk"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="非空" width="50" align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.notNull"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="生成策略" width="120" align="center">
                    <template slot-scope="scope">
                        <dx-select v-model="scope.row.pkGenerator" codeType="PK_GENERATOR_TYPE" :clearable="true"></dx-select>
                    </template>
                </el-table-column>
                <el-table-column label="默认SCOPE" width="120" align="center">
                    <template slot-scope="scope">
                        <dx-select v-model="scope.row.defaultScope" codeType="defaultvalue_scope_dict" :clearable="true"></dx-select>
                    </template>
                </el-table-column>
                
                <el-table-column label="默认值"  width="200" align="center">
                    <template slot-scope="scope">
                        <dx-suggesttext v-model="scope.row.defaultValue" :clearable="true" codeType="datamodel_defaultvalue_code"></dx-suggesttext>
                    </template>
                </el-table-column>
                <el-table-column label="转换器" width="200" align="center">
                    <template slot-scope="scope">
                        <dx-select v-model="scope.row.converter" :clearable="true" codeType="datamodel_conerter_code"></dx-select>
                    </template>
                </el-table-column>
                <el-table-column label="排序" width="80" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.orderList"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="deleteRow(scope.$index,scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <div style="width:150px;margin:20px auto;">
            <el-button type="primary" :loading="isLoading" @click="doSubmit"><span v-if="!isEdit">立即创建</span><span v-else>保存</span></el-button>
            <el-button @click="closeDialog">取消</el-button>
            <el-button v-if="in_array(form.seqType,['tree','seq'])" type="primary" :loading="isCompileLoading" @click="compileRun">编译验证</el-button>
        </div>
    </el-form>
</template>
<script>
import DxSelect from '../../Common/ui/dx-select'
import DxCheckBox from '../../Common/ui/dx-checkbox'
import DxRadio from '../../Common/ui/dx-radio'
import DxText from '../../Common/ui/dx-text'
import DxSuggesttext from '../../Common/ui/dx-suggesttext'
import DxTreeselect from '../../Common/ui/dx-treeselect'
import http from '../../../assets/js/http.js'
import toolkit from '../../../assets/js/toolkit.js'
import {codeProvider} from '../../../assets/js/provider.js'
export default {

    components : {
        DxSelect,
        DxCheckBox,
        DxRadio,
        DxText,
        DxSuggesttext,
        DxTreeselect
    },
    props :{
        id : String,
    },
    data(){
        return {
            dialogVisible : false,
            isloading : false,
            isCompileLoading : false,
            isEdit : false,
            referenceCodeType : '',
            referenceCodeList : [],
            form : {
                id : this.id,
                moduleName : '',
                name : '',
                dataType : 'table',
                categories : '1',
                sqlText : '',
                tableName : '',
                orderList : 10,
                enable : true,
                actionIntercept : '',
                fields : []
            },
            rules: {
                moduleName : [{ required: true, message: '请输入代码模型标识', trigger: 'blur' },
                              {pattern: /^[A-Za-z0-9_]+$/, message: '请输入英文字母', trigger: 'blur'}],
                name : [{ required: true, message: '请输入代码模型名称', trigger: 'blur' }],
                dataType : [{ required: true, message: '请选择代码类型', trigger: 'change' }],
                categories : [{ required: true, message: '请选择分类', trigger: 'change' }]
            }
        }
    },
    methods : {
        doSubmit(){

             this.$refs.baseForm.validate(vaild=>{

                if(vaild){
                    if(this.isEdit){
                        this.update();   
                    }else{
                        this.save();
                    }
                }
            });
          
        },
        handleCurrentChange(){

        },
        // compileRun(){
        //     this.$refs.baseForm.validate(vaild=>{

        //         if(vaild){
        //             this.isCompileLoading = !this.isCompileLoading
        //             let _data = Object.assign({},this.form);
        //             _data.enable = this.form.enable?1:0;
        //             _data.id = 0;
        //             _data.modifyDate = "";
        //             _data.createDate = "";
        //             this.apiPostForm('code/compileRun',_data).then(resp=>{

        //                 if(resp.code==200){
        //                     _g.toastMsg('success', '编译运行成功！')
                        
        //                 }else{
        //                     _g.toastMsg('error', resp.msg);
        //                 }
        //                 this.isCompileLoading = !this.isCompileLoading
        //             });


        //         }
        //     });
            
        // },
        addRow(){
            this.form.fields.push({});
        },
        deleteRow(index,row){
            this.form.fields.splice(index,1);
        },
        update(){

            this.isLoading = !this.isLoading
            let _data = Object.assign({},this.form);
            _data.isSystem = this.form.isSystem?this.form.isSystem:0;
            _data.modifyDate = moment(this.form.modifyDate).format('YYYY-MM-DD HH:mm:ss');
            _data.createDate = moment(this.form.createDate).format('YYYY-MM-DD HH:mm:ss');
            delete _data.keys;
            console.log(_data);
            this.apiPostForm('datamodel/updateSave',_data).then(resp=>{
                this.isLoading = !this.isLoading
                if(resp.code==200){
                    _g.toastMsg('success', '保存成功')
                    this.closeDialog();
                    this.$emit('submitData','update'); 
                }else{
                    _g.toastMsg('error',resp.msg);
                }
                
            });
        },

        save(){
            this.isLoading = !this.isLoading
            let _data = Object.assign({},this.form);
            _data.id = 0;
      
            delete _data.keys;
            this.apiPostForm('datamodel/addSave',_data).then(resp=>{

                this.isLoading = !this.isLoading
                if(resp.code==200){
                    _g.toastMsg('success', '保存成功')
                    this.closeDialog();
                    this.$emit('submitData','update'); 
                }else{
                    _g.toastMsg('error',resp.msg);
                }
                
            });
        },
        dataTypeChange(val){
            
            
        },
        closeDialog(){
            this.$emit('update:dialogVisible', false);
        },
        getNewFields(targets=[],sources=[],key){

            let result = [],deleteArr = [];

            for(let i=0;i<targets.length;i++){
                let flag = true;
                for(let j=0;j<sources.length;j++){
                    if(targets[i][key] == sources[j][key]){
                        flag = false;

                        result.push(sources[j])
                        continue;
                    }
                }
                if(flag){

                    result.push(targets[i]);
                }
            }

            return result;
        },
        getFields(){
            codeProvider.getList('table_colums_code_list' ,{tableName : this.form.tableName}).then(resp=>{
                if(resp){
                    let fields = [];
                    resp.forEach(item => {
                        let other = item.other;
                        other.remark = other.columnLabel;
                        other.orderList = 10;
                        fields.push(other);
                    });
                    if(this.isEdit){
                        let newFields = this.getNewFields(fields || [],this.form.fields || [],'columnName') || []; 
                        this.form.fields = newFields;
                    }else{
                        this.form.fields = fields;
                    }
                    
                }
  
            });
        },
        initData(){

            if(this.form.id){
                this.isEdit = true;
                _g.openGlobalLoading();
                this.apiGet('datamodel/getEntry?id='+this.form.id).then(resp=>{
                     _g.closeGlobalLoading();
                    if(resp.code == 200){
                        this.form = resp.data;
                    }else{
                        _g.toastMsg("warn",resp.msg);
                        setTimeout(()=>{
                            this.dialogVisible = false;
                        },1000);
                    }
                   
                });
            }else{
                this.isEdit = false;
            }
        }
    },
    created(){
        this.initData();
    },
    mounted(){
        this.routeName = this.$route.name;
        _g.closeGlobalLoading();
    },
    mixins:[http,toolkit]
}
</script>

<style scoped>
@import '../../../assets/css/framework.css';
/* .el-scrollbar{
    width: 400px;
} */
</style>
